package org.jactao.serialization.kryo;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.jactao.serialization.LSerializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by fanzetao on 2018/4/3.
 */
public class KryoSerializer implements LSerializer {

    Kryo kryo = new CustomKryo();

    @Override
    public byte[] serialize(Object obj) {

        ByteArrayOutputStream byteArrayOutputStream = null;
        Output output = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            output = new Output(byteArrayOutputStream);
            kryo.writeClassAndObject(output, obj);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayOutputStream.close();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return byteArrayOutputStream.toByteArray();
    }

    @Override
    public <T> T deserialize(byte[] content) {

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content);
        Input input = null;
        Object obj = null;
        try {
            input = new Input(byteArrayInputStream);
            obj = kryo.readClassAndObject(input);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayInputStream.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return (T) obj;
    }
}
